from logging.handlers import RotatingFileHandler
import logging
import threading
import configparser

class FileLog:
    def __init__(self, log_config):
        """   
        init config and get value   
        """

        self.logger = logging.getLogger('OutputLog')
        config = configparser.ConfigParser()
        config.read(log_config)

        mythread = threading.Lock()
        mythread.acquire()  # thread lock

        self.log_file_path = config.get('LOGGING', 'log_file_path')
        self.maxBytes = config.get('LOGGING', 'maxBytes')
        self.backupCount = int(config.get('LOGGING', 'backupCount'))
        self.outputConsole_level = int(config.get('LOGGING', 'outputConsole_level'))
        self.outputFile_level = int(config.get('LOGGING', 'outputFile_level'))
        self.outputConsole = int(config.get('LOGGING', 'outputConsole'))
        self.outputFile = int(config.get('LOGGING', 'outputFile'))
        self.formatter = logging.Formatter('[%(asctime)s][%(filename)s:%(lineno)d][%(levelname)s]%(message)s')
        mythread.release()  # thread lock relax

    def outputLog(self):
        """   
        output log to console and file   
        """
        if self.outputConsole == 1:
            # if true ,it should output log in console    
            console_handler = logging.StreamHandler()
            console_handler.setFormatter(self.formatter)
            self.logger.setLevel(self.outputConsole_level)
            self.logger.addHandler(console_handler)
        else:
            pass

        if self.outputFile == 1:
            file_handler = RotatingFileHandler(self.log_file_path, maxBytes=int(self.maxBytes), backupCount=self.backupCount)
            # define RotatingFileHandler, file output path, one file max byte, max backup number     
            file_handler.setFormatter(self.formatter)
            self.logger.setLevel(self.outputFile_level)
            self.logger.addHandler(file_handler)
        else:
            pass

        return self.logger